﻿using Surpass.Model.Dto.RequestParamsDto;
using Surpass.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Surpass.Common.Expressions;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResultModel;
using System.Transactions;
using Surpass.Repository.UnitOfWork;
using Surpass.Model;
using Surpass.Model.SysDomain;

namespace Surpass.Repository.Repository
{
    public class SysUserRepository : DataBase, ISysUserRepository
    {
        private readonly SurpassDbContext _surpassDbContext;


        public SysUserRepository(SurpassDbContext surpassDbContext) : base(surpassDbContext)
        {
            _surpassDbContext = surpassDbContext;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginParams"></param>
        
        public async Task<ResponseModel<SysUser>> Login(LoginParams loginParams)
        {
            ResponseModel<SysUser> responseModel = new ResponseModel<SysUser>();
            var result = await FirstAsync<SysUser>(u => u.Deleted == false && u.State == 1 && u.Email==loginParams.LoginEMail);
            if (result==null)
            {
                return responseModel.Fail(ResponseCode.LoginFail, "用户名不存在");
            }
            if (result.PassWord!=loginParams.LoginPass)
            {
                return responseModel.Fail(ResponseCode.LoginFail, "密码不存在");
            }
            return responseModel.Succeed(result);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="email"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageResponse<SysUser>> GetUserList(string uname, string email, int pageIndex = 1, int pageSize = 10)
        {

            Expression<Func<SysUser, bool>> userExpression = sysUser => sysUser.State == 1;
            if (!string.IsNullOrEmpty(uname))
            {
                userExpression = userExpression.And(c => c.NickName.Contains(uname));
            }
            if (!string.IsNullOrEmpty(email))
            {
                userExpression = userExpression.And(c => c.Email.Contains(email));
            }

            var query = await this.LoadPageEntitiesAsync(pageIndex, pageSize, userExpression, false, u => u.UserId);
            return query;
        }
        /// <summary>
        /// 注册用户
        /// 加入AOP【DbTransactionInterceptor】事务后该方法中不要加入try catch
        /// 否则没办法回滚
        /// </summary>
        /// <param name="sysUserParams"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        [DbTransactionInterceptor]
        public async Task<ResponseModel<bool>> AddSysUser(SysUserParams sysUserParams)
        {
            var result = new ResponseModel<bool>();
            int count = 0;
            var obj = new SysUser()
            {
                //UserId = sysUserParams.UserId,
                NickName = sysUserParams.NickName,
                PassWord = sysUserParams.PassWord,
                Sex = sysUserParams.Sex,
                Email = sysUserParams.Email
            };
            var sysUser = await AddAsync(obj);
            await SaveChangesAsync();
            if (!string.IsNullOrEmpty(sysUserParams.RoleIds))
            {
                foreach (var roleId in sysUserParams.RoleIds.Split(','))
                {
                    var userRoleRelation = new SysUserRoleRelation()
                    {
                        UserId = sysUser.UserId,
                        RoleId = Convert.ToInt64(roleId),
                        State = 1,
                        Deleted = false,
                        CreatedTime = DateTime.Now,
                        UpdatedTime = DateTime.Now,
                        UpdatedBy = 0,
                        CreatedBy = 0,
                    };
                    await AddAsync(userRoleRelation);
                }
            }
            
            count = await SaveChangesAsync();
            return count > 0 ? result.Succeed(true) : result.Fail("保存修改信息失败");
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="sysUserParams"></param>
        /// <returns></returns>
        [DbTransactionInterceptor]
        public ResponseModel<bool> EditSysUser(SysUserParams sysUserParams)
        {
            var result = new ResponseModel<bool>();
            int count = 0;
            var obj = new SysUser()
            {
                UserId = sysUserParams.UserId,
                NickName = sysUserParams.NickName,
                PassWord = sysUserParams.PassWord,
                Sex = sysUserParams.Sex,
                Email = sysUserParams.Email
            };
            //更新用户信息
            Update(obj);
            //删除相关角色
            LoadEntities<SysUserRoleRelation>(c => c.UserId == obj.UserId).Select(c => c.RoleId).ToList().ForEach(roleId=> {
                Delete<SysUserRoleRelation>(roleId, sysUserParams.UserId);
            });
           

            //更新
            if (!string.IsNullOrEmpty(sysUserParams.RoleIds))
            {
                foreach (var roleId in sysUserParams.RoleIds.Split(','))
                {
                    var userRoleRelation = new SysUserRoleRelation()
                    {
                        UserId = obj.UserId,
                        RoleId = Convert.ToInt64(roleId),
                        State = 1,
                        Deleted = false,
                        CreatedTime = DateTime.Now,
                        UpdatedTime = DateTime.Now,
                        UpdatedBy = 0,
                        CreatedBy = 0,
                    };
                    Update(userRoleRelation);
                }
            }
            count = SaveChanges();
            return count > 0 ? result.Succeed(true) : result.Fail("保存修改信息失败");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="sysUserParams"></param>
        /// <returns></returns>
        [DbTransactionInterceptor]
        public ResponseModel<bool> DeleteSysUser(SysUserParams sysUserParams)
        {
            int count = 0;
            ResponseModel<bool> result = new ResponseModel<bool>();

            //var sysUser = await FirstAsync<SysUser>(u => u.UserId == sysUserParams.UserId);
            Delete<SysUser>(sysUserParams.UserId);  //删除用户

            LoadEntities<SysUserRoleRelation>(u => u.UserId == sysUserParams.UserId).Select(u => u.RoleId).ToList().ForEach(roleId =>
            {
                Delete<SysUserRoleRelation>(roleId, sysUserParams.UserId);  //删除关系
            });

            count +=  SaveChanges();

            return count > 0 ? result.Succeed(true) : result.Fail("删除信息失败");
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="sysUsers"></param>
        /// <returns></returns>
        public async Task<ResponseModel<bool>> BatchAddAsync(List<SysUser> sysUsers)
        {
            var result = new ResponseModel<bool>();
            await _surpassDbContext.SysUsers.AddRangeAsync(sysUsers);
            var count = await _surpassDbContext.SaveChangesAsync();
            if (count>0)
            {
                return result.Succeed(true);
            }
            else
            {
                return result.Fail("批量添加失败");
            }
            
        }
    }
}
